#from django.shortcuts import render

# Create your views here.
from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
#from rest_framework.renderers import JSONRenderer
#from rest_framework.parsers import JSONParser
from measurement.import_probe_data_into_db import readDataFile
from measurement.import_probe_data_to_store import readDataFileToStore
from measurement.preprocess_probe_data import *
from measurement.algorithm_gum import *
from measurement.data_analysis import *
from measurement.data_compare import *
from measurement.report_figure_generate import *
from measurement.import_standard_data import readStandardProbeDataFile
from measurement.measurement_probe_data import measurementProbeData
from measurement.import_user_data_file import importUserDataFile
from measurement.import_device_parameters_file import readDeviceParameterDataFile
from measurement.measurement_utils import aprResetAllTaskStatus
from measurement.call_simulation_uncertainty import apiCallSimulationUncertainty
from measurement.open_dir_and_file import openDesttopDirOrFile
from measurement.algorithm_gum_figure import drawFigureForUncertaintyResult

from apps.vadmin.op_drf.response import SuccessResponse, ErrorResponse
from apps.vadmin.monitor.serializers import ServerSerializer
from apps.vadmin.op_drf.viewsets import CustomModelViewSet
from rest_framework.request import Request
from rest_framework.decorators import api_view

def test_django(reuqest):
    return HttpResponse("Hello Word!")

@csrf_exempt
def probe_data_list(reuqest):
    """
    Test API
    """
    reuqest.body.decode('utf-8')
    global s_app
    try:
        searchStr = str(reuqest.GET.get('searchStr'))
        type = int(reuqest.GET.get('type'))
        count = int(reuqest.GET.get('count'))

        #js = s_app.search(searchStr, topK=count, by=0, type=type)
        js = "test"

    except Exception as e:
        js = "[{'info':" + e.__doc__ + "}]"
    return HttpResponse(js, content_type = 'application/json;charset=utf-8')


@api_view(['GET', ])
def TestApiFun(reuqest):
    print("Measurement API doc test")
    return SuccessResponse(data={
        "msg": "GET Read probe data ..."
    })

@api_view(['POST', ])
def TestApiFun2(reuqest):
    print("Measurement API doc test")
    return SuccessResponse(data={
        "msg": "POST Read probe data ..."
    })


    """
    if request.method   == “GET”:
        # 查询所有数据
        snippets = Snippet.objects.all()
        # 序列化数据
        serializers = MeasurementSerializer(snippets, many=True)
    # 返回数据           return JsonResponse(serializers.data,   safe=False)

    elif request.method   == “POST”:
        # 解析提交的数据
        data   = JSONParser().parse(request)
        # 反解析序列数据
        serializers   = MeasurementSerializer(data=data)
        # 验证并保存数据
        if   serializers.is_valid():
            serializers.save()
        # 返回视图页面
        return  JsonResponse(serializer.data,   status=201)
    return  JsonResponse(serializer.errors, status=400)
    
    
    =====
    参考：
        if request.method == 'POST':
        #定义一个字典
        result={}
        username = request.POST.get('username')
        password=request.POST.get('password')
        #给字典赋值
        result['username'] = username
        result['password'] = password
        #把字典转化为json
        result=json.dumps(result)
        #告诉浏览器以json格式返回，格式是utf-8
        return HttpResponse(result,content_type='application/json;charset=utf-8')
        
    """
class TestApi(CustomModelViewSet):
    """
    测试API 文档
    """
    print("测试代码")
    def TestApiFun(self, request: Request, *args, **kwargs):
        print("Measurement API doc test")
        return HttpResponse("TestApiFun...")


class ReadData(CustomModelViewSet):
    serializer_class = ServerSerializer


    def return_func(self, ret):
        code = ret
        msg = ""
        data = ""
        if isinstance(ret,dict):
            if 'code' in ret:
                code = ret['code']
            if 'msg' in ret:
                msg = ret['msg']
            if 'data' in ret:
                data = ret['data']

        if code == 0:
            return SuccessResponse(data=data, msg=msg)
        else:
            return ErrorResponse(data=data, msg=msg, code=code)


    #测试
    def read_probe_data(self, request: Request, *args, **kwargs):

        #return HttpResponse("Read probe data ...")
        return SuccessResponse(data={
            "msg": "Read probe data ..."
        })

    #测试
    def readDataFileApi(self, request: Request, *args, **kwargs):
        param = eval(request.body)
        print(param)
        file_path = param.get('file_name')
        print("探测文件路径1：%s" % file_path)
        file = "D:/GBfiles/mycode/Workspace/MeasurementProject/test_data/激光雷达数据文件/WH_LD1_D_20210611181105_L2.dat"
        print("探测文件路径2：%s" % file)
        ret = readDataFile(file)

        return HttpResponse("readDataFile - Read probe data ...")


    #接口1：数据录入接口（202309版本废弃不用）
    def read_probe_data(self, request):
        """
        读取探测数据，支持单个文件及目录
        输入参数：
        {
            "task_id": "20220425111701001"        //时间戳，精确到毫秒，用于调用接口后，获取处理结果 --必填
            "user_id": 12                         //当前操作用户Id --必填
            "file_path": "D:/GBfiles/mycode/Workspace/MeasurementProject/test_data/lidar_data_f/L0_data" --必填
        }
        file_path 可为目录，或单个文件全路径
        """
        param = eval(request.body)
        print(param)
        #file_path_l0 = param.get('file_path_l0')
        #file_path_l2 = param.get('file_path_l2')
        #task_id = param.get('task_id')

        #print("接口参数：探测数据文件：%s, task_id: %s" % (file_path,task_id))
        print("接口参数：探测数据文件!")
        ret = readDataFile(param)
        #print(ret)

        return self.return_func(ret)


    def read_probe_data_to_store(self, request):
        """
        读取探测数据，支持单个文件及目录。读取的文件存在服务器，后续处理从服务器获取
        输入参数：
        {
            "task_id": "20220425111701001"        //时间戳，精确到毫秒，用于调用接口后，获取处理结果 --必填
            "user_id": 12                         //当前操作用户Id --必填
            "file_path": "D:/GBfiles/mycode/Workspace/MeasurementProject/test_data/lidar_data_f/L0_data" --必填
        }
        file_path 可为目录，或单个文件全路径
        """
        param = eval(request.body)
        print(param)

        #print("接口参数：探测数据文件：%s, task_id: %s" % (file_path,task_id))
        print("接口参数：探测数据文件（本地存储版）!")
        ret = readDataFileToStore(param)
        #print(ret)

        return self.return_func(ret)


    #接口2：数据预处理接口
    def preprocess_data(self, request):
        """
        预处理数据
        输入参数：
        {
               "task_id": "20220425111701001"        //时间戳，精确到毫秒，用于调用接口后，获取处理结果 --必填
               "data_id": "20220425111701001"       //要预处理的数据ID，即表bt_data_head的BatchId字段 --必填
                "height_standard_set":0             //高度统一化：0:未选;1:选中
                "time_standard_set":0             //时间分辨率统一化：0:未选;1:选中
                 "extreme_value_check":0            //极值检查：0:未选;1:选中
                "physics_consistency_check":0       //物理一致性检查：0:未选;1:选中
                 "time_consistency_check":0         //时间一致性检查：0:未选;1:选中
                 "statistics_check":0               //统计学检查：0:未选;1:选中
                "boxplot_check": 0                  //箱线图法检查：0:未选;1:选中
                "save_flag":0                       //预处理结果存入数据库：0:未选;1:选中
                "height_reslution":1                //同一高度分辨率，数据为高度间隔值（单位km）
                "time_reslution":0                  //统一时间分辨率：0:小时,1:分钟？（待确定）
                "filter_rule": 0                    //统计判断准则（枚举值）：0:无;1:拉伊达准则;2:格拉布斯准则;
                //3:狄克逊准则;4:稳健数据处理方法
                "exception_rule": 0                 //异常值处理（枚举值）：0:剔除;1:设为缺省值;2:保留   --必填
                "data_source":0                     //数据来源（枚举值）：0:新增数据;1:所有探测数据      --必填
                "temperature_max":0.0               //温度范围最大值（浮点数）
                "temperature_min":0.0               //温度范围最小值（浮点数）
                "density_max":0.0                   //密度范围最大值（浮点数）
                "density_min":0.0                   //密度范围最小值（浮点数）
                "wind_speed_max":0.0                //风速范围最大值（浮点数）
                "wind_speed_min":0.0                //风速范围最小值（浮点数）
        }
        """
        param = eval(request.body)
        print(param)
        #print("接口参数：探测数据文件：%s, task_id: %s" % (file_path,task_id))
        print("preprocess_data预处理过程执行")
        ret = processProbeData(param)

        return self.return_func(ret)


    #接口3：不确定度计算接口
    def perform_uncertainty_analysis(self, request):
        """
        读取探测数据，支持单个文件及目录
        输入参数：
        {
                "task_id": "20220425111701001"          //时间戳，精确到毫秒，用于调用接口后，获取处理结果 --必填
                "data_id": "20220425111701001"          //要预处理的数据ID，即表bt_data_head的BatchId字段 --必填
                "measure_method":0                      //评定算法（枚举值）：0:GUM,1:MCM  --必填
                "factor":0.0                            //包含因子（整数或小数）
                "data_source":0                         //数据来源（枚举值）：0:新增数据;1:所有预处理数据;2:未经预处理数据
                "save_flag":0                           //评定结果是否存库：0:未选;1:选中
        }
        """
        param = eval(request.body)
        print(param)
        #file_path = param.get('file_path')
        #task_id = param.get('task_id')

        print("perform_uncertainty_analysis接口参数!TODO")
        ret = performUncertainty(param)

        return self.return_func(ret)


    # 接口8：导入标准廓线数据（完成）
    def read_standard_probe_data_file(self, request):
        """
        读取标准廓线数据文件Excel，保存到数据库表
        输入参数：
        {
            "file_path": "D:/GBfiles/mycode/Workspace/MeasurementProject/test_data/standar_data_file/工作表-目标廓线.xlsx" --必填
        }
        """
        param = eval(request.body)
        print(param)
        file_path = param.get('file_path')

        print("接口参数：标准廓线数据文件：%s" % (file_path))
        ret = readStandardProbeDataFile(file_path)

        return self.return_func(ret)


    #接口6：数据分析界面对应工具 TODO
    def data_analysis_tools(self, request):
        """
        XXXXXX
        输入参数：
        {
            "xxxxxx": "xxxx"
        }
        """
        param = eval(request.body)
        print(param)

        print("data_analysis_tools接口参数!")
        ret = dataAnalysis(param)

        return self.return_func(ret)


    #接口7：数据比对界面对应工具
    def data_compare_tools(self, request):
        """
        XXXXXX
        输入参数：
        {
            "xxxxxx": "xxxx"
        }
        """
        param = eval(request.body)
        print(param)

        print("data_analysis_tools接口参数!")
        ret = dataCompare(param)

        return self.return_func(ret)


    #接口5：通过标准分辨率处理相关数据 TODO
    def data_standard_reslution(self, request):
        """
        XXXXXX
        输入参数：
        {
            "xxxxxx": "xxxx"
        }
        """
        param = eval(request.body)
        print(param)

        print("data_standard_reslution接口参数!")
        ret = dataResolutionConsolidated(param)

        return self.return_func(ret)


    # 接口4：不确定度一键评定：从导入--预处理--不确定度评定，一条龙 TODO
    def measurement_probe_data(self, request):
        """
        XXXXXX
        输入参数：
        {
            "xxxxxx": "xxxx"
        }
        """
        param = eval(request.body)
        print(param)

        print("measurement_probe_data接口参数!")
        ret = measurementProbeData(param)

        return self.return_func(ret)


    # 接口9：通过不确定度分量文件名称获取不确定度分量名称
    def get_uncertainty_component_file(self, request):
        """
        XXXXXX
        输入参数：
        {
            "xxxxxx": "xxxx"
        }
        """
        param = eval(request.body)
        print(param)

        print("get_uncertainty_component_file接口参数!")
        ret = getUncertaintyComponentFile(param)

        return self.return_func(ret)

    # 接口10：用户数据文件上传接口
    def import_user_data_file(self, request):
        """

        :param reques:
        :return:
        """
        param = eval(request.body)
        print(param)

        print("import_user_data_file接口参数!")
        ret = importUserDataFile(param)

        return self.return_func(ret)

    # 接口11：设备参数文件上传接口
    def import_device_parameter_data_file(self, request):
        """

        :param reques:
        :return:
        """
        print(request)
        param = eval(request.body)
        print(param)

        print("import_device_parameter_data_file接口参数!")
        ret = readDeviceParameterDataFile(param)

        return self.return_func(ret)

    # 接口12：调用第三方仿真模拟接口
    def call_simulation_program(self, request):
        """
        :param reques:
        :return:
        """
        param = eval(request.body)
        print(param)

        print("call_simulation_program接口参数!")
        ret = apiCallSimulationUncertainty(param)

        return self.return_func(ret)


    # 接口13：调用tkinter调用文件打开窗口(测试，Windows系统用)
    def open_desktop_dir_or_file(self, request):
        """
        :param reques:
        :return:
        """
        param = eval(request.body)
        print(param)

        print("open_desktop_dir_or_file接口参数!")
        ret = openDesttopDirOrFile(param)

        return self.return_func(ret)


    # 接口14：导出不确定度报告功能
    def data_report_figure_generation_tools(self, request):
        """
        :param reques:
        :return:
        """
        param = eval(request.body)
        print(param)

        print("data_report_figure_generation_tools接口参数!")
        ret = dataReportFigureGen(param)

        return self.return_func(ret)


    # 接口15：生成不确定度二维彩图（含等值线）功能
    def draw_figure_for_uncertainty_result(self, request):
        """
        :param reques:
        :return:
        """
        param = eval(request.body)
        print(param)

        print("draw_figure_for_uncertainty_result接口参数!")
        ret = drawFigureForUncertaintyResult(param)

        return self.return_func(ret)


    # 接口附一：重置任务表状态为0
    def reset_task_status(self, request):
        """
        :param reques:
        :return:
        """
        print(request)
        # param = eval(request.body)
        # print(param)
        param = {"task_type":-1}

        print("重置任务列表状态！")
        ret = aprResetAllTaskStatus(param)

        return self.return_func(ret)

    # 接口附一：重置运行时间（临时测试用）
    # def reset_running_time(self, request):
    #     """
    #     :param reques:
    #     :return:
    #     """
    #     print(request)
    #     param = eval(request.body)
    #     print(param)
    #
    #     print("重置任务列表状态！")
    #     ret = reset_run_time(param)
    #
    #     return self.return_func(ret)